<?php

namespace plugins\aliyunvod\controller;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib'.DIRECTORY_SEPARATOR.'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib'.DIRECTORY_SEPARATOR.'voduploadsdk' . DIRECTORY_SEPARATOR . 'aliyun-php-sdk-core/Config.php';   // 假定您的源码文件和aliyun-php-sdk处于同一目录

date_default_timezone_set('PRC');

use think\Db;
use think\db\Query;
use think\facade\Request;
use think\facade\Log;
use cmf\controller\PluginAdminBaseController;
use vod\Request\V20170321 as vod;
use core\DefaultAcsClient;
use core\Profile\DefaultProfile;

class AdminVodController extends PluginAdminBaseController
{
    public function _initialize()
    {
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            $this->error('未登录');
        }
    }


    /**
     * 添加视频
     */
    public function add()
    {
        $param = $this->request->param();
        $this->assign('is_edit',0);
        if(!empty($param['id']) && $param['id']>0){
           $video =  Db::connect()->name('plugin_aliyunvod')->where('id',$param['id'])->find();
           $this->assign('video',$video);
           $this->assign('is_edit',1);
        }

        $cate = Db::connect()->name('plugin_aliyunvod_category')
            ->where('is_del',0)
            ->order('create_time', 'ASC')
            ->select()
            ->toArray();
        $this->assign('cate',$cate);
        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del()
    {
        $param = $this->request->param();
        if(!empty($param['id']) && $param['id']>0){
           $up =  Db::connect()->name('plugin_aliyunvod')->where('id',$param['id'])->update(['status'=>0]);
            if($up){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }

    /**
     * url拉取
     */
    public function url()
    {
        $cate = Db::connect()->name('plugin_aliyunvod_category')
            ->where('is_del',0)
            ->order('create_time', 'ASC')
            ->select()
            ->toArray();
        $this->assign('cate',$cate);
        return $this->fetch();
    }

    /**
     * 分类列表
     */
    public function category()
    {   
        $param = $this->request->param();
        $isPage=false;

        $cate = Db::connect()->name('plugin_aliyunvod_category')
            ->where('is_del',0)
            ->order('create_time', 'DESC')
            ->paginate(10);
        $cate->appends($param);

        $this->assign('page', $cate->render());
        $this->assign('cate',$cate);

        return $this->fetch('/admin_vod/category');
    }
    /**
     * 添加 修改 分类
     */
    public function addCategory()
    {
        $param = $this->request->param();
        if(!empty($param['id']) && $param['id']>0){
           $cate =  Db::connect()->name('plugin_aliyunvod_category')->where('id',$param['id'])->find();
           $this->assign('cate',$cate);
        }
        return $this->fetch();
    }
    public function postCategory()
    {
        $param = $this->request->param();

        $cateName = $param['name'];
        $parentId=-1;

        $config = cmf_get_plugin_config('Aliyunvod');
        $accessKeyId = $config['AccessKeyId'];
        $accessKeySecret =  $config['AccessKeySecret'];

        try {
            
            $client = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            
            if(!empty($param['id']) && $param['id']>0){//修改 更新

                $cateId = $param['vod_cat_id'];
                $res = json_decode(json_encode($client->updateCategory($cateName,$cateId)),TRUE) ;

                if($res){
                    $up = Db::connect()->name('plugin_aliyunvod_category')->where('id',$param['id'])->update(['cate_name'=>$cateName]);
                    if($up){
                        $this->success('修改成功');
                    }else{
                        $this->error('修改失败');
                    }
                }else{
                        $this->error('修改失败');
                }
            }else{//添加
                $res = json_decode(json_encode($client->addCategory($cateName,$parentId)),TRUE);
                if($res['Category']){
                    $data=[
                        'vod_cat_id'=>$res['Category']['CateId'],
                        'cate_name'=>$res['Category']['CateName'],
                        'type'=>$res['Category']['Type'],
                        'level'=>$res['Category']['Level'],
                        'create_time'=>time()
                    ];
                    $add = Db::connect()->name('plugin_aliyunvod_category')->insertGetId($data);
                    if($add){
                        $this->success('添加成功');
                    }else{
                        $this->error('添加失败');
                    }
                }    
            }
            
        } catch (Exception $e) {
            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }
    /**
     * 删除分类
     */
    public function delCategory()
    {
        $param = $this->request->param();
        if(!empty($param['id'])){
            $config = cmf_get_plugin_config('Aliyunvod');
            $accessKeyId = $config['AccessKeyId'];
            $accessKeySecret =  $config['AccessKeySecret'];

            try {
                
                $client = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
                
                if(!empty($param['id'])){

                    $cateId = $param['vod_cat_id'];
                    $res = json_decode(json_encode($client->deleteCategory($cateId)),TRUE) ;

                    if($res){
                        $up = Db::connect()->name('plugin_aliyunvod_category')->where('id',$param['id'])->update(['is_del'=>1]);
                        if($up){
                            $this->success('删除成功');
                        }else{
                            $this->error('删除失败');
                        }
                    }else{
                            $this->error('删除失败');
                    }
                }
                
            } catch (Exception $e) {
                printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                    $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
            }
           
        }else{
            $this->error('参数异常');
        }
    }

    /**
     * 上传本地mp4视频
     */
    public function main(){
        
        $param = $this->request->param();

        $title = $param['title'];
        $cate = $this->request->param('category_id',0);
        $video = $_FILES['video'];


        if($video['name']!=''){
            $config = cmf_get_plugin_config('Aliyunvod');
            $accessKeyId = $config['AccessKeyId'];                    // 您的AccessKeyId
            $accessKeySecret =  $config['AccessKeySecret'];     // 您的AccessKeySecret
            $templateid = $config['TemplateGroupId'];
            $callbackurl = $config['CallbackURL'];
            $storageLoc = $config['StorageLocation'];

            $res = move_uploaded_file($video['tmp_name'],CMF_ROOT.'public/temp/'.$video['name']);
            if($res){
               try {

                    //上传后返回视频id
                    $vid = $this->UploadLocalVideo($accessKeyId, $accessKeySecret, CMF_ROOT.'public/temp/'.$video['name'], $title,$templateid, $callbackurl,$storageLoc);
                    //删除本地
                
                    if($vid){
                        
                        unlink(CMF_ROOT.'public/temp/'.$video['name']);
                        if(!empty($param['id'] && $param['id']>0)){//仅更新信息，不更新视频
                            $data=[
                                'video_id'=>$vid,
                                'title'=>$title,
                                'category_id'=>$cate
                            ];
                            $up = Db::connect('')->name('plugin_aliyunvod')->where('id',$param['id'])->update($data);
                            if($up){
                                $this->success('更新成功');
                            }
                        }else{
                            $data=[
                                'video_id'=>$vid,
                                'title'=>$title,
                                'category_id'=>$cate,
                                'create_time'=>time()
                            ];
                            $id = Db::connect('')->name('plugin_aliyunvod')->insertGetId($data);
                            if($id){
                                $this->success('上传完成');
                            }
                        }
                        

                    }
                    
                } catch (Exception $e) {
                    var_dump($e);
                } 
            }
        }else if(!empty($param['id'] && $param['id']>0)){//仅更新信息，不更新视频
            $data=[
                'title'=>$title,
                'category_id'=>$cate
            ];
            $up = Db::connect('')->name('plugin_aliyunvod')->where('id',$param['id'])->update($data);

            if($up){
                $this->success('更新成功');
            }
        }else{
            $this->error('请先上传视频！');
        }
        

        
        
    }

    /**
     * m3u8 url拉取
     */
    public function urlPull()
    {
        $param = $this->request->param();

        $title = $param['title'];
        $cate = $this->request->param('category_id',0);

        $config = cmf_get_plugin_config('Aliyunvod');
        $accessKeyId = $config['AccessKeyId'];
        $accessKeySecret =  $config['AccessKeySecret'];

        $webM3u8FileURL = $param['url'];
        $this->relog(json_encode($param));
        try {
            $res = $this->UploadWebM3u8($accessKeyId, $accessKeySecret, $webM3u8FileURL,$title);

            if($res){
                $this->relog(json_encode($res));

                $data=[
                    'video_id'=>$res,
                    'title'=>$title,
                    'category_id'=>$cate,
                    'create_time'=>time()
                ];
                $id = Db::connect('')->name('plugin_aliyunvod')->insertGetId($data);

                if(!$id){
                    $this->error('添加失败');
                }
            }
            $this->success('上传完成');
            
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    /**
     * 弹窗选择页
     */
    public function select()
    {
        $param = $this->request->param();
        $isPage=false;
        $start_time = !empty($param['start_time'])?strtotime($param['start_time']):0;
        $end_time = !empty($param['end_time'])?strtotime($param['end_time']):strtotime('+1 day');
        
        if($start_time!=0){
            $video = Db::connect()->name('plugin_aliyunvod')
                ->where(function (Query $query) use ($param,$isPage ) {
                    $keyword = empty($param['keyword']) ? '' : $param['keyword'];
                    if (!empty($keyword)) {
                        $query->whereOr('title', 'like', "%$keyword%");
                    }
                })
                ->whereBetweenTime('create_time', $start_time, $end_time)
                ->where('status',1)
                ->order('create_time', 'DESC')
                ->paginate(10);
                // var_dump(date('Y-m-d',$end_time));
            $this->assign('start_time',date('Y-m-d',$start_time));
            $this->assign('end_time',date('Y-m-d',$end_time));
        }else{
            $video = Db::connect()->name('plugin_aliyunvod')
            ->where(function (Query $query) use ($param,$isPage ) {
                $keyword = empty($param['keyword']) ? '' : $param['keyword'];
                if (!empty($keyword)) {
                    $query->whereOr('title', 'like', "%$keyword%");
                }
            })
            ->where('status',1)
            ->order('create_time', 'DESC')
            ->paginate(10);
            $this->assign('end_time',date('Y-m-d',$end_time));
        }
        
        $video->appends($param);

        $this->assign('page', $video->render());
        $this->assign('video',$video);

        

        $cate = Db::connect()->name('plugin_aliyunvod_category')
            ->where('is_del',0)
            ->order('create_time', 'DESC')
            ->select()
            ->toArray();
        $this->assign('cate',$cate);

        return $this->fetch();
    }
    // 上传本地视频
   public function UploadLocalVideo($accessKeyId, $accessKeySecret, $filePath, $title ,$templateid, $callbackurl,$storageLoc)
    {
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($filePath, $title);
            $uploadVideoRequest->setCateId(1000174912);
            //$uploadVideoRequest->setCoverURL("http://xxxx.jpg");
            //$uploadVideoRequest->setTags('test1,test2');
            $uploadVideoRequest->setStorageLocation($storageLoc);
            $uploadVideoRequest->setTemplateGroupId($templateid);
            $userData = array(
                "MessageCallback"=>array("CallbackURL"=>$callbackurl),
                "Extend"=>array("localId"=>"xxx", "test"=>"www")
            );
            $uploadVideoRequest->setUserData(json_encode($userData));
            

            $res = $uploader->uploadLocalVideo($uploadVideoRequest);
            

            return $res;
        } catch (Exception $e) {
            printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

    // 上传网络视频
    public function UploadWebVideo($accessKeyId, $accessKeySecret, $fileURL)
    {
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($fileURL, 'testUploadWebVideo via PHP-SDK');
            $res = $uploader->uploadWebVideo($uploadVideoRequest);
            
            return $res;
        } catch (Exception $e) {
            printf("testUploadWebVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

    // 上传本地m3u8视频
    public function UploadLocalM3u8($accessKeyId, $accessKeySecret, $m3u8FilePath , $title)
    {
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($m3u8FilePath, $title);
            // 调用接口解析m3u8的分片地址列表，如果解析结果不准确，请自行拼接地址列表(默认分片文件和m3u8文件位于同一目录)
            $sliceFiles = $uploader->parseM3u8File($m3u8FilePath);
            //print_r($sliceFiles);
            $res = $uploader->uploadLocalM3u8($uploadVideoRequest, $sliceFiles);
            print_r($res);
        } catch (Exception $e) {
            printf("testUploadLocalM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
                $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }

    // 上传网络m3u8视频
    public function UploadWebM3u8($accessKeyId, $accessKeySecret, $m3u8FileUrl,$title)
    {
        try {
            $uploader = new \AliyunVodUploader($accessKeyId, $accessKeySecret);
            $uploadVideoRequest = new \UploadVideoRequest($m3u8FileUrl, $title);
            // 调用接口解析m3u8的分片地址列表，如果解析结果不准确，请自行拼接地址列表(默认分片文件和m3u8文件位于同一目录)
            $sliceFileUrls = $uploader->parseM3u8File($m3u8FileUrl);
            //print_r($sliceFileUrls);
            $res = $uploader->uploadWebM3u8($uploadVideoRequest, $sliceFileUrls);
            
            return $res;
        } catch (Exception $e) {
            // printf("testUploadWebM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
            //     $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
        }
    }
    public function relog($word = '')
    {
        $word = is_array($word) ? var_export($word, 1) : $word;
        $fp = fopen( cmf_get_root().'temp/apilog.txt', 'a+');
        flock($fp, LOCK_EX);
        fwrite($fp, '执行日期：' . strftime('%Y%m%d%H%M%S', time()) . "\n" . $word . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}

